package com.lagou.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author Nocturne
 * @date 2021/5/10 0:00
 * @description SpringBoot + Mybatis实现动态数据源切换
 * 2. 创建数据源自动配置类，完成master、slave这两个数据源对象的创建
 */
@Configuration
public class MyDataSourceConfiguration {

	Logger logger = LoggerFactory.getLogger(MyDataSourceConfiguration.class);

	/**
	 * master DataSource
	 */
	@Bean
	@ConfigurationProperties(prefix = "spring.druid.datasource.master")
	public DataSource masterDataSource() {
		logger.info("create master dateSource...");
		return DataSourceBuilder.create().build();
	}

	/**
	 * slave DataSource
	 */
	@Bean
	@ConfigurationProperties(prefix = "spring.druid.datasource.slave")
	public DataSource slaveDataSource() {
		logger.info("create slave dateSource...");
		return DataSourceBuilder.create().build();
	}



	/**
	 * 程序需要数据源对象，先找到RoutingDataSource数据源对象，再由此对象找到存储在targetDaTaSources（Map）中的真实的数据源对象
	 * 4. 要将两个数据源对象添加到AbstractRoutingDataSource的targetSources这个Map中
	 */
	@Bean
	/*设置主数据源*/
	@Primary
	public DataSource primaryDataSource(
			@Autowired @Qualifier("masterDataSource") DataSource masterDataSource,
			@Autowired @Qualifier("slaveDataSource") DataSource slaveDataSource
	) {
		RoutingDataSource routingDataSource = new RoutingDataSource();

		HashMap<Object, Object> map = new HashMap<>();
		map.put("master", masterDataSource);
		map.put("slave", slaveDataSource);

		routingDataSource.setTargetDataSources(map);

		return routingDataSource;
	}
}
